package com.starbaba.core.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.starbaba.core.web.constant.WebConstants;
import com.starbaba.system.user.model.UserVO;

/**
 * @author Lai Weilong
 *
 */
public class MenuAccessMonitor implements Filter {
	
	public static boolean IS_MENU_MONITOR = true;

	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(MenuAccessMonitor.class);
	
	private FilterConfig filterConfig;
	
	private static final String IS_MENU_LOG = "menuLog";

	public MenuAccessMonitor() {
	}
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException{
		this.filterConfig = filterConfig;
		String menuLog = this.filterConfig.getInitParameter(IS_MENU_LOG);
		if(StringUtils.isNotBlank(menuLog)){
			IS_MENU_MONITOR = Boolean.valueOf(menuLog);
		}
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filterChain) throws IOException, ServletException {
		/*
		 * 1. 允许设置是否记录菜单访问日志
		 * 2. 非http请求不予处理
		 */
		if(!(IS_MENU_MONITOR && request instanceof HttpServletRequest)){
			//HttpServletRequest req1 = (HttpServletRequest)req;
			//System.out.println(req1.getRequestURI());
			filterChain.doFilter(request, response);
			return;
		}
		
		String info = getRequestInfo((HttpServletRequest) request, (HttpServletResponse) response);
		try {
			log2file(info, "Begin");
			filterChain.doFilter(request, response);
			log2file(info, "End");
		} catch (ServletException sx) {
			log2file(info, "End-ExpServ");
			throw sx;
		} catch (IOException iox) {
			log2file(info, "End-ExpIO");
			throw iox;
		}
	}

	private String getRequestInfo(HttpServletRequest request, HttpServletResponse response) {
		
		StringBuffer buffer = new StringBuffer(String.valueOf(System
				.currentTimeMillis())).append("|");

		try {
			String currentURL = request.getRequestURI();
			if (request.getQueryString() != null) {
				currentURL = currentURL + "?" + request.getQueryString();
			}

			if (currentURL != null) {
				String contextPath = request.getContextPath();
				currentURL = currentURL.replaceFirst(contextPath, "");
			}

			String sessionid = null;
			String opercode = null;

			HttpSession session = request.getSession();

			if (session != null) {
				sessionid = session.getId();

				UserVO user = (UserVO) session.getAttribute(WebConstants.SESSION_ATTRIBUTE_USER);
//				UserVO user = (UserVO) SessionManager.getSession(request, response).getAttribute(WebConstants.SESSION_ATTRIBUTE_USER); 
				if (user != null) {
					opercode = user.getUserid();
				}
			}

			buffer.append(opercode).append("|").append(sessionid)
					.append("|").append(request.getRemoteHost()).append("|")
					.append(currentURL);

		} catch (Throwable e1) {
			e1.printStackTrace();
		}

		return buffer.toString();
	}

	private void log2file(String info, String type) {
		StringBuffer buffer = new StringBuffer();
		buffer.append(type).append("|").append(info);
		logger.info(buffer.toString());
	}

	@Override
	public void destroy() {
	}

}
